#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
#endif

// 精准忙等待和休眠（单位：微秒）
void busy_sleep(int busy_percent) {
    const int total_time = 100000; // 100ms
    int busy_time = total_time * busy_percent / 100;
    int sleep_time = total_time - busy_time;

#ifdef _WIN32
    LARGE_INTEGER freq, start, now;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&start);
    do {
        QueryPerformanceCounter(&now);
    } while ((now.QuadPart - start.QuadPart) * 1000000 / freq.QuadPart < busy_time);
    Sleep(sleep_time / 1000); // Windows 休眠单位为毫秒
#else
    struct timespec start, now;
    clock_gettime(CLOCK_MONOTONIC, &start);
    long elapsed;
    do {
        clock_gettime(CLOCK_MONOTONIC, &now);
        elapsed = (now.tv_sec - start.tv_sec) * 1000000 + (now.tv_nsec - start.tv_nsec) / 1000;
    } while (elapsed < busy_time);
    usleep(sleep_time);
#endif
}

// 线程函数：持续占用 CPU
void* cpu_load(void* arg) {
    while (1) {
        busy_sleep(50); // 50% 占用率
    }
    return NULL;
}

int main() {
#ifdef _WIN32
    SYSTEM_INFO sysInfo;
    GetSystemInfo(&sysInfo);
    int num_cores = sysInfo.dwNumberOfProcessors;

    // 动态分配线程句柄数组
    HANDLE* threads = (HANDLE*)malloc(num_cores * sizeof(HANDLE));
    if (threads == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 1;
    }

    for (int i = 0; i < num_cores; i++) {
        threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)cpu_load, NULL, 0, NULL);
        if (threads[i] == NULL) {
            fprintf(stderr, "线程创建失败\n");
            free(threads);
            return 1;
        }
        SetThreadAffinityMask(threads[i], 1ULL << i);
    }

    WaitForMultipleObjects(num_cores, threads, TRUE, INFINITE);
    free(threads); // 释放内存
#else
    int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
    pthread_t threads[num_cores];
    for (int i = 0; i < num_cores; i++) {
        pthread_create(&threads[i], NULL, cpu_load, NULL);
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(i, &cpuset);
        pthread_setaffinity_np(threads[i], sizeof(cpu_set_t), &cpuset);
    }
    for (int i = 0; i < num_cores; i++) {
        pthread_join(threads[i], NULL);
    }
#endif
    return 0;
}